System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

41% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Day 6: E-Commerce & Transactions
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Design a Code Deployment System
Design an API Gateway
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design Stripe Payment Gateway
Image

Here is the system design for Stripe (Payment Gateway), focusing on the core payment processing flow.

1. Problem Definition and scope

  • Main User Groups:
    • Merchants: Developers integrating our API to process payments.
    • Customers: End-users entering card details to buy goods.
  • Main Actions:
    • Tokenizing sensitive card data (so merchants don't have to handle it).
    • Processing a charge (taking money).
    • Refunding a charge.
  • Scope:
    • We will focus on the Core Payment API (Tokenization, Charges, Refunds).
    • Out of Scope: Recurring billing (subscriptions), physical Point of Sale (POS) hardware, and cryptocurrency payments.
Image

2. Clarify functional requirements

Must Have:

  • Tokenization: Users send card data securely to us and get a safe "token" back. The merchant never stores raw card numbers.

  • Create Charge: Merchants can charge a specific amount using a token.

  • Idempotency: The API must guarantee that retrying a request (e.g., after a network timeout) does not result in a double charge.

  • Transaction Status: Merchants can query if a payment is Pending, Succeeded, or Failed.

  • Refunds: Merchants can reverse a transaction.

  • Ledger: System must track merchant balances (money in vs money out) accurately.

Nice to Have:

  • Webhooks: Asynchronous notifications to merchants when a payment succeeds.

  • Fraud Detection: Basic blocking of suspicious IP addresses.

Image

3. Clarify non-functional requirements

  • Reliability: Strong Consistency is mandatory. We are dealing with money; we cannot use "eventual consistency" for the ledger or payment status.

  • Availability: Extremely high (99.999%). If we are down, merchants lose revenue.

  • Latency:

    • Internal processing: < 200ms.
    • End-to-End: Limited by external banks (2-5 seconds). We must handle these long waits gracefully.
  • Security: PCI DSS Level 1 Compliance. We must isolate the storage and processing of raw credit card numbers.

  • Scale: Support 10 million transactions per day.

Image

4. Back of the envelope estimates

Traffic:

  • 10 million transactions / day.
  • 10,000,000 / 86,400 sec ≈ 115 TPS (Average).
  • Payments are bursty (e.g., Black Friday). Assume 10x peak.
  • Peak: ≈ 1,200 TPS.
  • Note: While 1,200 TPS is low for a social app, financial transactions are "heavy" (encryption, ACID locks, external calls), so the complexity is high.

Storage:

  • Assume 2 KB per transaction (metadata, ledger entries, logs).
  • 10,000,000 x 2 KB = 20 GB / day.
  • 20 GB x 365 ≈ 7.3 TB / year.
  • This fits in a standard relational database, though we will likely shard for write throughput.
Image

5. API design

We will use a REST API. We mandate the use of an Idempotency-Key header for all state-changing operations.

1. Create Token (Client-side)

  • POST /v1/tokens
  • Body: { "number": "4242...", "exp_month": 12, "exp_year": 2025, "cvc": "123" }
  • Response: { "id": "tok_123", "card": { "last4": "4242", ... } }
  • Note: This goes to a separate "Vault" service.

2. Create Charge

  • POST /v1/charges
  • Header: Idempotency-Key: <unique-uuid>
  • Body: { "amount": 2000, "currency": "usd", "source": "tok_123" }
  • Response: { "id": "ch_999", "status": "succeeded", "amount": 2000 }
  • Errors: 402 Payment Required (Declined), 409 Conflict (Idempotency error).

3. Refund Charge

  • POST /v1/refunds
  • Body: { "charge": "ch_999", "amount": 1000 } (Optional partial refund).

6. High-level architecture

We separate the system into a PCI Zone (handles raw cards) and a Standard Zone (business logic) to minimize security scope.

  • Token Vault: The only service that touches raw card numbers. It encrypts them, stores them in the Secure DB, and returns a token (tok_123).

  • API Gateway: Handles authentication (API Keys), rate limiting, and routing.

  • Payment Service: The core brain. It checks idempotency, creates the transaction record, and orchestrates the call to the bank.

  • PSP Adapter: Translates our internal request format into the specific format of the external bank (e.g., Stripe, Chase, Adyen).

  • Core DB: Stores transaction metadata and the financial ledger.

  • Workers: Handle background tasks like sending webhooks or email receipts.

Image

7. Data model

We use PostgreSQL for ACID compliance. Financial data requires strict consistency.

1. Merchants

  • id (PK), name, api_key_hash, webhook_url.

2. Charges

  • id (PK), merchant_id (FK), token_id, amount (Integer in cents), currency.
  • status: ENUM (CREATED, PENDING, SUCCEEDED, FAILED).
  • gateway_reference: ID returned by the external bank.

3. Idempotency_Keys

  • key (PK), merchant_id (PK), response_payload, locked_at, status.
  • Purpose: Ensures we return the exact same response for retries without re-running logic.

4. Ledger (Double Entry)

  • id (PK), transaction_id, account (e.g., 'Merchant Balance', 'Platform Fees'), debit, credit.
  • Purpose: Immutable log of money movement. Debits must equal credits. We sum these rows to get a balance.

8. Core flows end to end

In a payment system, code logic translates directly into money movement. Unlike a social app where losing a "like" is acceptable, losing a payment record or charging a user twice is not.

We will break the system down into three critical lifecycles:

  1. Tokenization: Securing the sensitive data (PCI Compliance).
  2. Charge Processing: The "Happy Path" of moving money.
  3. Failure Handling: The "Unhappy Path" (Timeouts and Reconciliation).

Flow 1: Card Tokenization (The Security Firewall)

Goal: We must capture the user's credit card details without the Merchant’s backend (or our own non-secure services) ever seeing the raw numbers.

The "Direct Post" Pattern:

  1. Client Action: The user enters card details on the frontend (Browser or Mobile App).
  2. Direct Request: The frontend sends this data directly to our Token Vault Service, bypassing the Merchant’s backend entirely.
  3. Encryption:
  • The Vault validates the card (Luhn algorithm).
  • It encrypts the card number using a hardware-backed key (HSM).
  • It stores the encrypted data in a Secure DB and generates a reference token (e.g., tok_123).
  1. Response: The Vault returns tok_123 to the frontend.
  2. Handoff: The frontend sends tok_123 to the Merchant’s Backend.
  • Why this matters: The Merchant now has a safe reference to the card (tok_123) to charge it. If their database is hacked, attackers only find useless tokens, not raw credit card numbers.
Image

Flow 2: Create Charge (The Transaction Path)

Goal: Use the token (tok_123) to capture money. This flow requires strict Idempotency (preventing double charges) and Atomic State Management.

Scenario: A merchant sends a request POST /charges to charge $20.00.

Phase 1: The Idempotency Check (The Guard Rail)

Why? Networks are flaky. If a merchant clicks "Pay" twice, or if the first request times out, they will retry. We must ensure we only charge them once.

  1. Check Cache: The Payment Service checks Redis for the Idempotency-Key (e.g., uuid-555).
  • Hit (Completed): If the key exists and has a saved response (e.g., "Success"), return that saved response immediately. Stop here.
  • Hit (Processing): If the key exists but is marked "IN_PROGRESS", it means another thread is already working on this. Return 409 Conflict.
  • Miss (New): If the key is new, create an entry in Redis marked "IN_PROGRESS" with a short TTL (Time To Live). Proceed to Phase 2.

Phase 2: Persistence (The Intent)

Why? Before talking to the outside world, we write down what we intend to do. This acts as a "checkpoint."

  1. Create Record: Insert a row into the Charges Table in the Core DB.
  • Status: PENDING
  • Amount: 2000 (cents)
  • Token: tok_123
  1. Commit: We commit this transaction before calling the bank.
  • Senior Tip: If we kept the DB transaction open while waiting for the bank (which can take 2-5 seconds), we would hold database locks for too long, destroying system performance.

Phase 3: Execution (The External Call)

Why? This is the point of no return. We execute the logic.

  1. Detokenization: The Payment Service passes tok_123 to the PSP Adapter.
  2. Secure Retrieval: The Adapter calls the Token Vault (via internal mTLS). The Vault decrypts the card number in memory and returns it to the Adapter.
  3. External Call: The Adapter formats the request (ISO 8583 or JSON) and calls the External Bank (e.g., Chase, Visa).
  • Note: This is a blocking call. It can take 2–5 seconds.

Phase 4: The Completion (State Resolution)

Why? We must update our records to match reality.

  1. Bank Response Handling: The bank returns a status. We open a new DB transaction to save the result.
  • Case A: Success (Approved):

  • Update Charge Status: PENDING SUCCEEDED.

  • Atomic Ledger Write: Inside the same transaction, insert Ledger rows:

  • Debit: Bank_Receivable ($20.00) Money the bank owes us.

  • Credit: Merchant_Balance ($19.40) Money the merchant can withdraw.

  • Credit: Platform_Fees ($0.60) Our revenue.

  • Case B: Decline (Insufficient Funds):

  • Update Charge Status: PENDING FAILED.

  • Return 402 Payment Required to the merchant.

  • Case C: Timeout: (See "Flow 3" below).

  1. Finalize Idempotency: Update the Redis key uuid-555 with the final JSON response.
Image

Flow 3: Handling Timeouts (Reconciliation)

The Interview "Curveball": What happens if the Bank charges the card, but the network connection breaks before we get the reply?

The Problem: The Bank thinks the status is "Success," but our Database says "Pending." We are in an unknown state. The Solution: We do not retry immediately (risk of double charge). We rely on Reconciliation.

  1. Immediate Action: If the external call times out (e.g., > 30s), we throw a 504 Gateway Timeout to the merchant. We leave the Charge status as PENDING.
  2. Reconciliation Worker: A background process runs (or polls) to fix these stuck states.
  • It finds all Charges that have been PENDING for > 2 minutes.
  • It queries the Bank's "Inquiry API" using our Transaction ID.
  1. Self-Healing:
  • If Bank says "Paid": We update our DB to SUCCEEDED and write the Ledger rows.
  • If Bank says "Not Found": We update our DB to FAILED.
Image

9. Caching and read performance

  • Idempotency Keys: Cached in Redis (with persistence) to allow fast locking on retries.
  • Merchant Config: API keys and settings cached in Redis (LRU).
  • What NOT to Cache:
    • Transaction Status: We never cache payment status. We always read from the Primary DB to ensure the merchant sees the absolute latest state.
    • Balances: Always calculated from the Ledger or a materialized view in the DB.

10. Storage, indexing and media

  • Primary Storage: PostgreSQL.
  • Indexes:
    • idempotency_key: Unique constraint for correctness.
    • merchant_id + created_at: For merchant dashboards ("Show my recent payments").
    • gateway_reference: For reconciling bank reports.
  • Encryption:
    • At Rest: Database disk encryption (AES-256).
    • Application Level: The Token Vault encrypts sensitive columns before writing to the DB using keys stored in an HSM (Hardware Security Module).

11. Scaling strategies

  • Database Partitioning (Sharding):
    • Shard by Merchant_ID to keep all data for one business on one node.
    • Risk: "Hot Shard" if a merchant is huge (e.g., Amazon).
    • Mitigation: For top 1% merchants, we might shard by Charge_ID.
  • Read Replicas:
    • Direct all GET traffic (Dashboard, Reports) to Read Replicas.
    • Keep Master free for POST (Charges/Refunds).
  • Async Workers:
    • Offload heavy work (Webhooks, Emails, Analytics) to a Kafka queue. This keeps the API response time low.

12. Reliability, failure handling and backpressure

This is the most critical section for Fintech.

  • Reconciliation (The Safety Net):
    • Networks fail. A bank might approve a charge, but the connection drops before we get the reply.
    • Fix: We run a nightly Reconciliation Job. It downloads a "Settlement File" from the Bank and compares it row-by-row with our DB. Any mismatch is auto-corrected or flagged for human review.
  • Circuit Breakers:
    • If "Bank A" times out 50% of requests, we trip the circuit breaker.
    • Traffic is fast-failed locally ("Provider Unavailable") to prevent our thread pools from exhausting.
  • Idempotency:
    • Ensures safety on retry. If a merchant clicks "Pay" twice, we only charge the card once.

13. Security, privacy, and abuse

  • PCI DSS Scope:
    • The Token Vault is isolated in a separate VPC. Only whitelisted apps can talk to it. The rest of the company only sees tok_123.
  • Authentication:
    • API Keys (sk_live_...).
    • mTLS (mutual TLS) for internal service-to-service communication.
  • Rate Limiting:
    • Token Bucket algorithm per merchant.
    • Strict limits on "Card Testing" (trying many different cards from one IP).

14. Bottlenecks and next steps

  • Bottleneck: External Bank Latency.
    • Next Step: Smart Routing. Integrate with multiple banks. If Bank A is slow, route traffic to Bank B.
  • Bottleneck: Ledger Lock Contention.
    • Next Step: Use "Buffered Writes." Instead of locking the Merchant Balance row for every charge, insert "pending credit" rows and sum them up asynchronously in the background.

Summary

  1. Security: We used a Token Vault to isolate PCI data.

  2. Correctness: We used Idempotency keys and a Double-Entry Ledger to ensure money is never lost or counted twice.

  3. Reliability: We added Reconciliation jobs to handle the inevitable network failures between us and the banks.

Design Amazon Shopping Cart
Design Stock Exchange
Mark as Completed

On this page

1. Problem Definition and scope

2. Clarify functional requirements

3. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High-level architecture

7. Data model

8. Core flows end to end

Flow 1: Card Tokenization (The Security Firewall)

Flow 2: Create Charge (The Transaction Path)

Flow 3: Handling Timeouts (Reconciliation)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy, and abuse

14. Bottlenecks and next steps

Summary